package engine.motionDetection;

import java.awt.image.BufferedImage;


/**
 * 
 * calibration of the webcam
 * @author HINB
 *
 */
public class CalibrationLocal {
	
	/* *********************************************************
	 * Static Methods
	 * ********************************************************* */
	/**
	 * calibrate the webcam by getting the average color of the hand
	 * of the player
	 * @param image the image to get the color of the hand from
	 * @return the red, green and blue value for the average color
	 * the first cell of the array is red then green then blue.
	 */
	public static int[] calibrate(BufferedImage image)
	{		
		int color[] = {0,0,0}; //[0]: red,[1]: green,[2]: blue
		
		System.out.println("engine.motionDetection : calibrate");	
		
		//get the size of the image
		int width = image.getWidth();
		int height = image.getHeight();
		
		//get the color of the pixel in the calibration area
		//the calibration area being 4/10 of width and height, centered
		for(int j=(3*(height/10)); j<((7*(height/10))-1); j++)
		{
			for(int i=(3*(width/10)); i<((7*(width/10))-1); i++)
			{	
				int rgb = image.getRGB(i, j);
				
				color[0] = color[0] + ((rgb>>16) & 0xFF);
				color[1] = color[1] + ((rgb>>8) & 0xFF);
				color[2] = color[2] + (rgb & 0xFF);			
			}
		}
		
		//compute the average
		for(int j=0; j<3; j++)
		{
			color[j] = color[j]/((((7*(width/10))-1)-(3*(width/10)))*(((7*(height/10))-1)-(3*(height/10))));
		}
		
		//Motion returns the average color
		return color;
	}
	
	/**
	 * validate or not the calibration.
	 * @param image the image used for calibration
	 * @param margin the margin to apply on the color average of the hand
	 * @param average color average of the hand
	 * @param low_margin low margin for the number of pixel detected
	 * @param high_margin high margin for the number of pixel detected
	 * @return false if too much or too many pixel detected true if it's ok
	 */
	public static boolean isCalibrationOK(BufferedImage image,int margin, int[] average, int low_margin, int high_margin)
	{		
		boolean validation = false;
		int [] coord;
		
		coord = HandTrackingLocal.track(image, margin, average, low_margin, high_margin);
		System.out.println("position " + coord[0] + " , " + coord[1] + "\n");
		if((coord[0]!=-1)&&(coord[1]!=-1)){
			validation = true;
		}
		
		return validation;
	}
}
